
const superagent = require('superagent');
const getAccessToken = require('tools/dd/getAccessToken');

module.exports = async ctx => {
    try {
        const company = ctx.headers["company-id"];
        const dept_id = ctx.query.dept_id;
        const accessToken = await getAccessToken(company);
        ctx.body = await getDepartment(accessToken, dept_id);
        ctx.status = 200;
    } catch (error) {
        ctx.status = error.code || 500;
        ctx.body = error
    }
}

/** 获取userid */
function getDepartment(accessToken, dept_id) {
    return new Promise((resolve, reject) => {
        superagent.post('https://oapi.dingtalk.com/topapi/v2/department/listsub')
            .query({ 'access_token': accessToken })
            .send({dept_id})
            .end((error, res) => {
                try {
                    if (error) throw error;
                    if (res.body.errcode !== 0) throw res.body
                    resolve(res.body.result);
                } catch (error) {
                    reject({ code: 501, data: error })
                }
            })
    })
}